package org.itboys.mobile.service.mysql.mobile.income;

import org.itboys.commons.utils.tools.ListUtil;
import org.itboys.commons.utils.tools.LongUtil;
import org.itboys.kitchen.dao.income.KitchenIncomeProductMapper;
import org.itboys.kitchen.dao.income.KitchenIncomeRecordMapper;
import org.itboys.kitchen.entity.mysql.income.KitchenIncome;
import org.itboys.kitchen.entity.mysql.income.KitchenIncomeProduct;
import org.itboys.kitchen.entity.mysql.income.KitchenIncomeRecord;
import org.itboys.kitchen.entity.mysql.order.KitchenOrder;
import org.itboys.mobile.common.SundayCommonConstants;
import org.itboys.mobile.util.NumberUtil;
import org.itboys.mongodb.service.BaseMySqlService;
import org.itboys.param.ParamUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.security.provider.Sun;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 作者：jiangxiong
 * 日期：2017年5月8日
 * 联系方式 ：empty90911@126.com
 * 描述：农厨_钱包（收益）_产品_service_mobile
 */
@Service
public class KitchenMobileIncomeService extends BaseMySqlService<KitchenIncome>{
    @Autowired
    private KitchenIncomeRecordMapper incomeRecordMapper;
    @Autowired
    private KitchenIncomeProductMapper incomeProductMapper;

    /**
     * 查找用户钱包（收益主表）
     * @param memberId
     * @return
     */
    @Transactional
    public KitchenIncome findOne(Long memberId){
        Map<String,Object> param = new HashMap<String, Object>();
        param.put("memberId", memberId);
        KitchenIncome income=null;
        List<KitchenIncome> incomes=super.select(param);
        if(ListUtil.isNotNull(incomes)){
            income=incomes.get(0);
        }else {
            income=new KitchenIncome(memberId);
            super.insert(income);
        }
        return income;
    }


    /**
     * 生成交易记录
     * @param memberId
     * @param type
     * @param orderNo
     * @param payAmount

     * @return
     */
    @Transactional
    public String  generateRecord2(Long memberId,Integer type,String orderNo,BigDecimal payAmount,List<KitchenIncomeRecord> incomeRecords,String out_trade_no){
            //查询用户的钱包主表

        KitchenIncome income = findOne(memberId);

        Double thisAmount=0.00;//本次交易金额
        //1，充值创建订单时，已经写入了充值记录。
        //2，此方法是充值支付成功后，使充值记录生效
        if(type== SundayCommonConstants.income_record_type_charge){
            //更改充值记录状态
            for(KitchenIncomeRecord incomeRecord:incomeRecords){
                incomeRecord.setStatus(1);
                incomeRecord.setRemark(incomeRecord.getRemark()+out_trade_no);
                incomeRecordMapper.update(incomeRecord);
            }
           // income=findOne(memberId);
            //更新钱包主表
            BigDecimal amount = new BigDecimal(thisAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
            income.setTotalRevenue(income.getAbleRevenue().add(amount));
            income.setAbleRevenue(income.getAbleRevenue().add(amount));
            super.update(income);


            //消费扣减
        }else if(type==SundayCommonConstants.income_record_type_consume){
            logger.info("--开始生产余额交易记录");
            thisAmount=payAmount.doubleValue()*(-1);
            BigDecimal amount = new BigDecimal(thisAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
            //生成记录
            KitchenIncomeRecord incomeRecord= new KitchenIncomeRecord(
                     memberId,  income.getMemberId(),amount,
                     income.getAbleRevenue(),SundayCommonConstants.income_record_type_consume,1, "商城消费，订单编号："+orderNo);
            incomeRecordMapper.insert(incomeRecord);
            logger.info("--当前余额-"+income.getAbleRevenue()+"当前交易金额="+amount);
            //更改钱包(收益主表)
             income.setAbleRevenue(income.getAbleRevenue().add(amount));
             income.setFrozenRevenue(income.getFrozenRevenue().subtract(amount));
            logger.info("--交易后余额-"+income.getAbleRevenue());
             super.update(income);
          //系统返还
        }else if(type==SundayCommonConstants.income_record_type_cancel){
           // thisAmount=payAmount.doubleValue()*(-1);
            BigDecimal amount = new BigDecimal(thisAmount).setScale(2,BigDecimal.ROUND_HALF_UP);
            //生成记录
            KitchenIncomeRecord incomeRecord= new KitchenIncomeRecord(
                    memberId,  income.getMemberId(),amount,
                    income.getAbleRevenue(),SundayCommonConstants.income_record_type_cancel,1, "订单取消，订单编号："+orderNo);
            incomeRecordMapper.insert(incomeRecord);
            //更改钱包(收益主表)
            income.setAbleRevenue(income.getAbleRevenue().add(amount));
            income.setFrozenRevenue(income.getFrozenRevenue().subtract(amount));
            super.update(income);
        }
        return null;
    }
    /**
     * 获取充值产品
     */
    /**
     *
     * @param memberId
     * @return
     */
    public List<Map<String,Object>> getProducts(Long memberId){
        Map<String,Object>  param = new HashMap<String,Object>();
        List<KitchenIncomeProduct> products=incomeProductMapper.select(param);
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        for(KitchenIncomeProduct product:products){
            Map<String,Object>  result  = new HashMap<String,Object>();
            result.put("id",product.getId());
            result.put("baseAmount",product.getBaseAmount());
            result.put("freeAmount",product.getFreeAmount());
            result.put("totalAmount",product.getBaseAmount().add(product.getFreeAmount()));
            results.add(result);
        }
        return  results;
    }

    /**
     * 充值-创建订单
     * @param memberId
     * @param productId
     * @return
     */
    public Map<String,Object> createOrder(Long memberId,Long productId){
        //准备返回结果
        Map<String,Object>  result = new HashMap<String,Object>();
        String orderIds = "";
        KitchenIncome income=findOne(memberId);
        //查询充值产品
        KitchenIncomeProduct incomeProduct=incomeProductMapper.find(productId);
        //充值金额
        KitchenIncomeRecord incomeRecord_charge= new KitchenIncomeRecord(
                memberId,  income.getMemberId(),incomeProduct.getBaseAmount(),
                income.getAbleRevenue(),SundayCommonConstants.income_record_type_charge,0, "余额充值，充值编号：");
        incomeRecordMapper.insert(incomeRecord_charge);
        orderIds+=incomeRecord_charge.getId()+",";

        //赠送金额
        KitchenIncomeRecord incomeRecord_charge_free= new KitchenIncomeRecord(
                memberId,  income.getId(),incomeProduct.getFreeAmount(),
                income.getAbleRevenue(),SundayCommonConstants.income_record_type_free,0, "充值赠送，充值编号：");
        incomeRecordMapper.insert(incomeRecord_charge_free);
        orderIds+=incomeRecord_charge_free.getId();
        result.put("payAmount",incomeRecord_charge.getAmount().setScale(2,BigDecimal.ROUND_HALF_UP));//本次付款金额
        result.put("orderIds",orderIds);
        result.put("isNeedToPay",1);//订单是否需要支付
        result.put("type",2);//余额充值
        result.put("info","isNeedToPay标识是否需要支付。0否，1是。type是标识支付订单类型，1是订单，2是余额充值");

        return  result;
    }
    /**
     *获取交易记录
     * @param request
     * @param memberId
     */
    public  List<Map<String,Object>> getRecords(HttpServletRequest request,Long memberId){
        List<Map<String,Object>> results = new ArrayList<Map<String,Object>>();
        Map<String,Object>  param = ParamUtil.packageMysqlPageParam(request,"remark","type");
        param.put("memberId",memberId);
        param.put("status",1);
        List<KitchenIncomeRecord> incomeRecords=incomeRecordMapper.select(param);
        for(KitchenIncomeRecord incomeRecord:incomeRecords){
            Map<String,Object>  result  = new HashMap<String,Object>();
            result.put("id",incomeRecord.getId());
            result.put("amount",incomeRecord.getAmount());
            result.put("type",incomeRecord.getType());
            result.put("typeStr",incomeRecord.getTypeStr());
            result.put("remark",incomeRecord.getRemark());
            result.put("createTime",incomeRecord.getCreateTime());
            result.put("createDate",incomeRecord.getCreateDate());
            results.add(result);
        }
        return results;
    }
}
